<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 商品类
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2014-05-27 11:31:33 +0800 (二, 2014-05-27) $
 * @version : $Id: goods_model.php 107 2014-05-27 03:31:33Z spike $
 * @rev     : $Revision: 107 $
 */
class Goods_model extends CI_Model
{
    static $MAX_IMG;
    public function __construct()
    {
        parent::__construct();
        self::$MAX_IMG = 1;
    }

    // --------------------------------------------------------------------

    /**
     * [分页浏览]
     * @param  [array]  $params  [条件]
     * @param  [int]    $page    [当前页]
     * @param  [int]    $size    [页数，只允许app_config中"pagesize"的值]
     * @param  [string] $orderby [排序]
     * @return [array]
     */
    public function browse_goods($params, $page = NULL, $size = NULL, $orderby = 'popular_desc')
    {
        $output = array(
            'size' => 0,
            'data' => array(),
            'total'=> 0,
        );

        $where_in = NULL;
        $where = "`is_delete` = '".UNDELETED."'";

        // 名称搜索
        if( ! empty($params['name']) )
        {
            $name    = xss_clean(trim($params['name']));
            $where  .= " AND (`goods_sn` LIKE '%".$name."%'";
            $where  .= " OR `name` LIKE '%".$name."%'";
            $where  .= " OR `subname` LIKE '%".$name."%')";
        }

        // 类目搜索
        if( ! empty($params['cat']) )
        {
            $this->load->dao('Category_dao');
            $category = $this->Category_dao->get_one(array(
                '`seo_name` LIKE' => $params['cat'],
            ));

            if( ! $category)
            {
                return $output;
            }

            $where .= " AND `category_id` = '".(int)$category['category_id']."'";
        }

        // 属性搜索
        if( preg_match('/^[\d]+\-[\d]+$/', $params['attr']) )
        {
            $arr           = split('-', $params['attr']);
            $attr_id       = (int)$arr[0];
            $attr_value_id = (int)$arr[1];

            $this->load->dao('Goods_attr_dao');
            $goods_attr = $this->Goods_attr_dao->get(array(
                'attr_id'       => $attr_id,
                'attr_value_id' => $attr_value_id,
                'is_delete'     => UNDELETED
            ));
            $goods_sns = array_pick($goods_attr, 'goods_sn');
            $where_in['goods_sn'] = $goods_sns;
        }

        $pagesize = $this->config->item('pagesize');
        $size     = isset($pagesize[$size]) ? $size : 8;
        $offset   = intval(($page-1)*$size) > 0 ? intval(($page-1)*$size) : 0;
        $total    = 0;

        switch (strtolower(trim($orderby))) 
        {
            case 'new_desc':
                    $orderby = '`create_time`  DESC';
                break;

            case 'price_desc':
                    $orderby = '`base_price` DESC';
                break;

            case 'popular_desc':
            default:
                    $orderby = '`popular` DESC';
                break;
        }

        $this->load->dao('Goods_dao');
        $data = $this->Goods_dao->get_in(
            $where_in,
            $where, 
            '*', 
            $orderby, 
            $size, 
            $offset, 
            TRUE, 
            $total
        );

        $output['size']  = $size; 
        $output['data']  = $data; 
        $output['total'] = $total;

        return $output;
    }

    // --------------------------------------------------------------------
    
    /**
     * [获得一个商品]
     * @param  [string]     $goods_sn
     * @param  [bool]       $enable        [是否排除"关闭状态"]
     * @return [array/false]
     */
    public function get_goods($goods_sn, $enable = TRUE, $with_attr = FALSE, $with_desc = FALSE )
    {
        if( ! validate($goods_sn, 'GOODS_SN') )
        {
            $this->set_error("获取商品失败：商品编码[{$goods_sn}]格式不正确。");
            return FALSE;
        }
        
        $where = array(
            'goods_sn'  => $goods_sn,
            'is_delete' => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = GOODS_STATUS_ON;
        }

        $this->load->dao('Goods_dao');
        $goods = $this->Goods_dao->get_one($where);
        if( ! $goods)
        {
            $this->set_error("获取商品失败：无法找到商品。[{$goods_sn}]");
            return FALSE;
        }

        if( $with_attr === TRUE )
        {
            $this->load->dao('Goods_attr_dao');
            $attr = $this->Goods_attr_dao->get(
                array(
                    'goods_sn' => $goods_sn,
                    'is_delete'=> UNDELETED,
                ),
                array(
                    'attr_id','attr_value_id'
                )
            );
            foreach ($attr as $a) 
            {
                $goods['attr'][$a['attr_id']][] = $a['attr_value_id'];
            }
        }

        if( $with_desc === TRUE )
        {
            $this->load->dao('Goods_desc_dao');
            $desc = $this->Goods_desc_dao->get_one(
                array(
                'is_delete' => UNDELETED,
                'goods_sn'  => $goods_sn,
                'type'      => GOODS_DESC_TYPE_NORMAL,
                ),
                array(
                    'desc'
                )
            );
            $goods['desc'] = html_entity_decode(htmlspecialchars_decode($desc['desc']));
        }

        return $goods;
    }

    /**
     * [更新受欢迎度]
     * @param  [string] $goods_sn
     * @return [bool] 
     */
    public function update_popular($goods_sn)
    {
        if( ! validate($goods_sn, 'GOODS_SN') )
        {
            return FALSE;
        }

        $this->load->dao('Goods_dao');
        $this->Goods_dao->update_popular($goods_sn);
        
        return TRUE;
    }
}